package diona.snippet

import com.google.gdata.client.contacts.ContactsService
import java.net.URL
import scala.collection.JavaConversions._
import net.liftweb.util._
import Helpers._
import com.google.gdata.data.contacts.{ContactEntry, ContactFeed}
import com.google.gdata.client.Query
import diona.model.{User, GoogleAuth}
import diona.auth.GoogleOperations

/**
 * User: anton
 * Date: 20.03.11 18:11
 */
class ContactsList
{
  def contacts =
  {
    val currentToken: Option[GoogleAuth] = GoogleAuth.byUser(User.currentUser.get)
    currentToken match {
      case None => GoogleOperations.requestAuthorization("/contacts/contactsList")
      case Some(token) => displayContacts(token)
    }
  }

  private def displayContacts(authInfo: GoogleAuth): CssSel =
  {
    val service = new ContactsService("share-share-1")
    service.setAuthSubToken(authInfo.authToken.value)

    val feedUrl = new URL("https://www.google.com/m8/feeds/contacts/default/full")

    def getName(contact: ContactEntry): String =
    {
      if (contact.getName != null && contact.getName.getFullName != null)
        contact.getName.getFullName.getValue
      else ""
    }

    def getEmail(contact: ContactEntry): String =
    {
      if (contact.getEmailAddresses != null)
        contact.getEmailAddresses.toList.map(_.getAddress).mkString(", ")
      else ""
    }
    val query = new Query(feedUrl)
    query.setMaxResults(Int.MaxValue)
    val feed = service.getFeed(query, classOf[ContactFeed])
    ".contactItem *" #> feed.getEntries.toList.map(e =>
      ".name *" #> getName(e) &
        ".email" #> getEmail(e)
    )
  }
}